//import Workflow from '@/libs/workflow';
import axios from 'axios';

let vm;
let flag = false;
let planTableName = '';
let success = 0;
let fail = 0;
let successFlag = false;
let cardStatus, vmThis;
export default {
    getVariable(_this, params) {
        return new Promise((resolve, reject) => {
            _this.$get(_this.$API.getBillVariableAndUrl, params).then(result => {
                resolve(result.data);
            });
        });
    },
    // 批量审批接口
    workflowCheck(_this, options, status, selectedData, businessId) {
        vm = this;
        vmThis = _this;
        if (selectedData.length < 1) {
            _this.warning('请选择数据');
            return;
        }
        let dataList = [];
        let ids = [];
        selectedData.forEach(item => {
            ids.push(item.id);
        });
        let params = {
            billId: ids,
            businessId: businessId
        };
        vm.getVariable(_this, params).then(result => {
            let resList = result;
            success = 0;
            fail = 0;
            resList.forEach((item, index) => {
                _this.options.variables = item.variable;
                _this.options.bizExtra = item.bizExtra;
                let options = {};
                options.bizTypeCode = item.businessTypeCode;
                options.rgCode = item.regionId;
                options.unitCode = item.orgCode;
                options.variables = item.variable;
                options.menuId = item.menuId;
                options.businessKey = ids[index];
                options.taskId = item.taskId;
                options.procDefId = item.procDefId;
                options.nodeId = item.nodeId;
                options.procInstId = item.procInstId;
                dataList[index] = _this.options = options;
            });
            if (dataList.length === 1) {
                //只有一条时走单个的审批接口
                _this.options = dataList[0];
                _this.options.onComplete = vm.approveComplete;
                vm.approve(_this.options);
            } else {
                //多个的走批量的审批
                options.list = dataList;
                vm.batchApprove(_this, options, false, status);
            }
        });
    },
    // 单据页完成回调
    billComplete(ret) {
        if (ret.error) {
            vmThis.error('操作失败');
        } else {
            vm.completeEnd(vmThis, cardStatus);
        }
    },
    // 工作流完成回调
    completeEnd(_this, status) {
        if (_this.disabledFlag) {
            _this.topBtns.forEach((item, i) => {
                if (item.action !== 'ADD' && item.action !== 'CLOSE') {
                    _this.$set(item, 'disabled', '1');
                } else if (item.action === 'ADD' || item.action === 'CLOSE') {
                    _this.$set(item, 'disabled', '0');
                }
            });
        }
        _this.success('操作成功');
    },
    batchStart(_this, options, status, dataList) {
        options.list = dataList;
        this.startApprove(_this, options, status);
    },
    startApprove(_this, options, status) {
        vm = this;
        cardStatus = status;
        vmThis = _this;
        options.onComplete = vm.approveComplete;
        $workflow.batchStart(options);
    },
    // 批量送审完成
    batchComplete(ret) {
        if (ret.error) {
            fail++;
            successFlag = false;
        } else {
            success++;
            successFlag = true;
        }
        return successFlag;
    },
    // 批量审批完成
    approveComplete(ret) {
        if (ret.error) {
            vmThis.error('操作失败');
        } else {
            vm.batchEnd(vmThis);
        }
    },
    // 工作流完成后的逻辑控制
    batchEnd(_this, flag) {
        _this.freshTable();
        if (!flag) {
            _this.success('操作成功');
        }
    },
    async batchWorkFlow(businessKey, formDefinedData, _this) {
        planTableName = formDefinedData.tableName;
        let startI = document.URL.indexOf('menuid'); // 获取menuid位置
        let menuStr = document.URL.substring(startI); // 截取menuid之后的部分
        let andI = menuStr.indexOf('&'); // 获取第一个&的位置
        let menuId = menuStr.substring(7, andI);
        const t = this;
        vm = _this;
        /* commonComplete:'0',不走通用的complete */
        formDefinedData.onComplete = t.batchComplete;
        formDefinedData.businessKey = businessKey;
        if (await $workflow.validator.isWorkflowStarted(businessKey)) {
            // formDefinedData.menuId = menuId
            $workflow.approve(formDefinedData);
        } else {
            formDefinedData.bizExtra = _this.options.bizExtra;
            formDefinedData.userCode = localStorage.getItem('userCode');
            $workflow.start(formDefinedData);
        }
    },
    async workFlow(businessKey, formDefinedData, _this, thisFlag) {
        planTableName = formDefinedData.tableName;
        let startI = document.URL.indexOf('menuid'); // 获取menuid位置
        let menuStr = document.URL.substring(startI); // 截取menuid之后的部分
        let andI = menuStr.indexOf('&'); // 获取第一个&的位置f
        let menuId = menuStr.substring(7, andI);
        const t = _this;
        vm = this;
        console.log(formDefinedData);
        /* commonComplete:'0',不走通用的complete */
        formDefinedData.onComplete = vm.billComplete;
        formDefinedData.businessKey = businessKey;
        if (await $workflow.validator.isWorkflowStarted(businessKey)) {
            formDefinedData.variables = _this.options.variables;
            $workflow.approve(formDefinedData);
        } else {
            formDefinedData.variables = _this.options.variables;
            formDefinedData.bizExtra = _this.options.bizExtra;
            console.log(formDefinedData.bizExtra);
            console.log(_this.options.bizExtra);
            formDefinedData.userCode = localStorage.getItem('userCode');
            $workflow.start(formDefinedData);
        }
        // }
    },
    approve(options, thisFlag) {
        $workflow.approve(options);
    },
    // 批量审批
    batchApprove(_this, options, thisFlag, status) {
        vm = this;
        cardStatus = status;
        vmThis = _this;
        options.onComplete = vm.approveComplete;
        $workflow.batchApprove(options);
    },
    reject(options, thisFlag) {
        $workflow.back(options);
    },
    async withdraw(_this, options) {
        let params = {
            businessKey: options.businessKey,
            businessCode: options.bizTypeCode
        };
        await _this.$get(_this.$API.getTaskId, params).then(res => {
            const newOptions = { ...options };
            newOptions.taskId = res.data;
            $workflow.validator.canTaskCancel(newOptions).then(result => {
                if (result) {
                    $workflow.cancel(options);
                } else {
                    vmThis.warning('该单据不可收回');
                }
            });
        });
    },
    // 列表页工作流
    listSubmit(vmThis, selectedData, selectedStatus, businessId) {
        const v = this;
        let _this = null;
        if (vmThis !== undefined) {
            _this = vmThis;
        } else {
            _this = vm;
        }
        if (selectedData.length < 1) {
            vmThis.warning('请选择数据');
            return;
        }
        if (selectedStatus.indexOf('-1') > -1 || selectedStatus.indexOf('-2') > -1) {
            vmThis.warning('存在草稿单据，不允许送审！');
            return;
        }
        let ids = [];
        selectedData.forEach(item => {
            ids.push(item.id);
        });
        let params = {
            billId: ids,
            businessId: businessId
        };
        v.getVariable(vmThis, params).then(result => {
            let resList = result;
            success = 0;
            fail = 0;
            resList.forEach(item => {
                vmThis.options.variables = item.variable;
                vmThis.options.bizExtra = item.bizExtra;
                let businessKey = item.billId;
                let options = {};
                options.bizTypeCode = item.businessTypeCode;
                options.rgCode = item.regionId;
                options.unitCode = item.orgCode;
                options.variables = item.variable;
                options.menuId = item.menuId;
                if (item.taskId) {
                    options.taskId = item.taskId;
                }
                if (item.procDefId) {
                    options.procDefId = item.procDefId;
                }
                if (item.nodeId) {
                    options.nodeId = item.nodeId;
                }
                if (item.procInstId) {
                    options.procInstId = item.procInstId;
                }
                v.batchWorkFlow(businessKey, options, vmThis);
            });
            let loop = setInterval(function () {
                if (success + fail === selectedData.length) {
                    if (success === 0) {
                        vmThis.warning('送审失败');
                    } else if (fail === 0 && success !== 0) {
                        vmThis.success(`成功送审${success}条数据`);
                    } else if (fail !== 0 && success !== 0) {
                        vmThis.success(`成功送审${success}条数据,${fail}条数据送审失败`);
                    }
                    if (successFlag) {
                        v.batchEnd(_this, successFlag);
                    }
                    clearInterval(loop);
                }
            }, 100);
        });
    },
    // 列表页通用工作流
    listWorkFlow(type, _this, selectedData, status, businessId) {
        vm = this;
        if (selectedData.length < 1) {
            vm.warning('请选择数据');
            return;
        }
        let dataList = [];
        let ids = [];
        selectedData.forEach(item => {
            ids.push(item.id);
        });
        let params = {
            billId: ids,
            businessId: businessId
        };
        vm.getVariable(_this, params).then(result => {
            let resList = result;
            resList.forEach((item, index) => {
                let newOptions = {};
                newOptions.variables = item.variable;
                newOptions.bizExtra = item.bizExtra;
                newOptions.bizTypeCode = item.businessTypeCode;
                newOptions.rgCode = item.regionId;
                newOptions.unitCode = item.orgCode;
                newOptions.variables = item.variable;
                newOptions.menuId = item.menuId;
                newOptions.userCode = item.userCode;
                newOptions.taskId = item.taskId;
                newOptions.businessKey = ids[index];
                dataList[index] = newOptions;
                _this.options.userCode = item.userCode;
            });
            switch (type) {
                case 'takeBack':
                    vm.batchCancel(_this, _this.options, status, dataList);
                    break;
                case 'reject':
                    vm.batchBack(_this, _this.options, status, dataList);
                    break;
            }
        });
    },
    //批量收回
    batchCancel(_this, options, status, dataList) {
        options.list = dataList;
        this.cancelApprove(_this, options, false, status);
    },
    cancelApprove(_this, options, thisFlag, status) {
        vm = this;
        cardStatus = status;
        vmThis = _this;
        options.onComplete = vm.approveComplete;
        $workflow.batchCancel(options);
    },
    // 批量退回
    batchBack(_this, options, status, dataList) {
        options.list = dataList;
        this.backApprove(_this, options, false, status);
    },
    backApprove(_this, options, thisFlag, status) {
        vm = this;
        cardStatus = status;
        vmThis = _this;
        options.onComplete = vm.approveComplete;
        $workflow.batchBack(options);
    },
    // 单据工作流
    billWorkFlow(type, _this, dataSource, businessId) {
        vm = this;
        vmThis = _this;
        let billId = [];
        billId.push(dataSource[_this.mainCode].id);
        let businessKey = '';
        let params = {
            billId: billId,
            businessId: businessId
        };
        vm.getVariable(_this, params).then(result => {
            _this.disabledFlag = true;
            let resList = result;
            resList.forEach(item => {
                businessKey = dataSource[_this.mainCode].id;
                _this.options.variables = item.variable;
                _this.options.bizExtra = item.bizExtra;
                _this.options.bizTypeCode = item.businessTypeCode;
                _this.options.rgCode = item.regionId;
                _this.options.unitCode = item.orgCode;
                _this.options.variables = item.variable;
                _this.options.menuId = item.menuId;
                _this.options.userCode = item.userCode;
                _this.options.businessKey = businessKey;
                if (item.taskId) {
                    _this.options.taskId = item.taskId;
                }
                if (item.procDefId) {
                    _this.options.procDefId = item.procDefId;
                }
                if (item.nodeId) {
                    _this.options.nodeId = item.nodeId;
                }
                if (item.procInstId) {
                    _this.options.procInstId = item.procInstId;
                }
                switch (type) {
                    case 'submit':
                        vm.workFlow(businessKey, _this.options, _this, flag);
                        break;
                    case 'audit':
                        _this.options.onComplete = vm.billComplete;
                        vm.approve(_this.options);
                        break;
                    case 'takeBack':
                        _this.options.onComplete = vm.billComplete;
                        vm.withdraw(_this, _this.options);
                        break;
                    case 'reject':
                        _this.options.onComplete = vm.billComplete;
                        vm.reject(_this.options);
                        break;
                }
            });
        });
    }
};
